package com.xjnt.frameworks.web.beetl.tags;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.beetl.core.GeneralVarTagBinding;

import com.jfinal.kit.StrKit;
import com.xjnt.frameworks.core.BaseModel;

public class SelectTag extends GeneralVarTagBinding {

	private List<?> modelList;
	private String field;
	private String value;
	private String defaultOption;

	private void init() {
		modelList = (List<?>) getAttributeValue("models");
		field = getAttributeValue("field").toString();
		Object val = getAttributeValue("value");
		value = val == null ? null : val.toString();
		Object option = getAttributeValue("defaultOption");
		defaultOption = option == null ? null : option.toString();
	}

	@Override
	public void render() {
		init();

		StringBuilder html = new StringBuilder();
		html.append("<select");

		// 自带属性完全拷贝
		@SuppressWarnings("unchecked")
		Map<String, Object> map = (Map<String, Object>) this.args[1];
		Set<Entry<String, Object>> mapEntry = map.entrySet();
		Iterator<Entry<String, Object>> itEntry = mapEntry.iterator();
		while (itEntry.hasNext()) {
			Entry<String, Object> entry = itEntry.next();
			String key = entry.getKey();
			if (key.equalsIgnoreCase("models") || key.equalsIgnoreCase("field") || key.equalsIgnoreCase("value")
					|| key.equalsIgnoreCase("defaultOption")) {
				continue;
			}
			Object value = entry.getValue();
			html.append(" ").append(key).append("=\"").append(String.valueOf(value)).append("\" ");
		}
		// 拷贝结束
		html.append(">");
		if (StrKit.notBlank(defaultOption)) {
			html.append("<option value=\"\" >").append(defaultOption).append("</option>");
		}
		String[] fields = field.split(",");
		for (Object obj : modelList) {
			BaseModel<?> model = (BaseModel<?>) obj;
			String oVal = model.getStr(fields[0]);
			String oName = model.getStr(fields[1]);
			html.append("<option value=\"").append(oVal).append("\" ");
			if (value != null && value.equals(oVal)) {
				html.append(" selected=\"selected\"");
			}
			html.append(" >");
			html.append(oName).append("</option>");
		}
		html.append("</select>");
		try {
			ctx.byteWriter.writeString(html.toString());
			this.doBodyRender();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

}
